package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.builder.FullOrderData;
import com.itheima.reggie.builder.FullOrderDataBuilder;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.pojo.*;
import com.itheima.reggie.service.*;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    ShoppingCartService shoppingCartService;

    @Autowired
    UserService userService;
    @Autowired
    AddressBookService addressBookService;
    @Autowired
    OrderDetailService orderDetailService;

    @Override
    @Transactional
    public void submit(Orders orders) {
        //获取当前用户id
        Long userId = BaseContext.getCurrentThread();
        long orderId = IdWorker.getId();
        orders.setUserId(userId);
        orders.setId(orderId);

        FullOrderDataBuilder fullOrderDataBuilder = new FullOrderDataBuilder(
                orders,
                shoppingCartService,
                userService,
                addressBookService);


        log.info("订单数据：{}", orders);
//必须先处理订单  后处理订单详情
        FullOrderData fullOrderData = fullOrderDataBuilder.buildOrderDetails().buildOrders().build();

        //查询当前用户的购物车数据
        Orders orders1 = fullOrderData.getOrders();
        List<OrderDetail> orderDetails = fullOrderData.getOrderDetails();
        this.save(orders1);
        //订单表
        orderDetailService.saveBatch(orderDetails);

        //清空购物车
        shoppingCartService.remove(new QueryWrapper<ShoppingCart>().eq("user_id", userId));
    }
}
